import { encode, decode } from 'js-base64'; // 可忽略此处ts报错
import { constantRoutes } from '@/router/index';
import { asyncRoutes } from '@/router/asyncRoutes';
import { removeOriginToken } from '@/api/user';

const KEY_TOKEN = 'token';
const KEY_SYS_TOKEN = 'sys_token';
const KEY_DATA_PERMISSION = 'data_permission';

// token
export function getToken() {
  return localStorage.getItem(KEY_TOKEN);
}

export function getSysToken() {
  return localStorage.getItem(KEY_SYS_TOKEN);
}

export function setToken(token: string) {
  return localStorage.setItem(KEY_TOKEN, token);
}

export function setSysToken(token: string) {
  return localStorage.setItem(KEY_SYS_TOKEN, token);
}

export function removeToken() {
  return localStorage.removeItem(KEY_TOKEN);
}

/**
 * 添加动态路由和菜单
 */
interface MenuItem {
  id?: string;
  code: string;
  name?: string;
  path: string;
  redirect?: string;
  menuId?: string;
  menuName?: string;
  component?: object;
  mode?: any;
  meta?: any;
  isNest?: boolean;
  children?: any[];
}
interface RouteItem {
  id?: string;
  code?: string;
  name?: string;
  path: string;
  redirect?: string;
  menuId?: string;
  menuName?: string;
  component?: object;
  mode?: any;
  meta?: any;
  isNest?: boolean;
  children?: any[];
}

const asyncRoutesHandle = function (
  routes: any[] | undefined,
  menus: any[] | undefined,
  permissions: any[]
) {
  // step three in one 
  permissions.map((item: MenuItem) => {
    let route: RouteItem | undefined;
    let menu: RouteItem | undefined;
    // MostImportant async and current router two in one
    // item code is async router code but current component name
    const routerItem = asyncRoutes[item.code];
    // if current router component name == async router component code
    if (routerItem) {
      routerItem.meta.title = item.menuName || routerItem.meta.title || '';
      menu = {
        path: routerItem.path,
        id: item.code,
        isNest: routerItem.isNest || routerItem.meta.isNest,
        meta: routerItem.meta,
        children: [],
      };
      if (!item.mode?.isExternal) {
        // 如果不是外链菜单，才需要生成路由
        route = {
          path: routerItem.path,
          name: routerItem.name,
          // l3 use two layout component  
          component: routerItem.component,
          meta: routerItem.meta,
        };
        if (routerItem.redirect) route.redirect = routerItem.redirect;
      }
    } else {
      // not have the same component name 
      menu = {
        path: item.path,
        id: item.menuId,
        isNest: item.isNest || item.mode?.isNest,
        meta: { title: item.menuName, ...item.mode },
        children: [],
      };
      if (!item.mode?.isExternal) {
        // 如果不是外链菜单，才需要生成路由
        route = {
          path: item.path,
          name: item.code,
          component: item.component,
          meta: { title: item.menuName, ...item.mode },
        };
        if (item.redirect) route.redirect = item.redirect;
      }
    }
    if (route && item.children && item.children.length > 0) {
      route.children = [];
    }
    if (item.children && item.children.length > 0) {
      asyncRoutesHandle(route?.children, menu?.children, item.children);
    }
    routes?.push(route);
    menus?.push(menu);
    return item;
  });
};

export function setAsyncRoutes(permissions: any[]) {
  // step two get in one routes params
  // menus current router page one box
  const constantMenu = constantRoutes[0]?.children || [];
  const menus: any[] = [...constantMenu];
  const routes: any[] = [];
  // in one routes [] / current header box / async 
  asyncRoutesHandle(routes, menus, permissions);
  return { menus, routes };
}
// #

/**
 * 固定路由组织成菜单
 * @param menus 
 * @param routes 
 */
export function routerToMenu(menus: any[] | undefined, routes: any[]) {
  let menu: RouteItem | undefined;
  routes.map((item: MenuItem) => {
    menu = {
      path: item.path,
      id: item.name,
      isNest: item.isNest || item.mode?.isNest,
      meta: { ...item.meta },
      children: [],
    };
    if (item.children && item.children.length > 0) {
      routerToMenu(menu?.children, item.children);
    }
    if(!item.meta?.notMenu) menus?.push(menu);
    return item;
  })
}

/**
 * 登出
 */
export async function logout(isApiLogout = false) {
  if (getToken() && isApiLogout) {
    await removeOriginToken();
  }
  // localStorage.clear();
  window.location.replace('./#/login');
  window.location.reload();
}
